package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Spring容器
 *
 * @author xzy
 * @date 2021/11/310:34
 */
public class XiaozyApplicationContext {

    /**
     * 配置类
     */
    private Class configClass;

    /**
     * 单例池
     * beanName --> singletonBean
     */
    private ConcurrentMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    /**
     * Bean定义信息
     */
    private ConcurrentMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    /**
     * 后置处理器
     * TODO: 实现对BeanPostProcessor的排序
     */
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public XiaozyApplicationContext(Class configClass) {
        this.configClass = configClass;

        /*
         * 解析配置类
         */

        // 1.扫描组件   ComponentScan注解 --> 扫描路径 --> 扫描 --> BeanDefinition --> BeanDefinitionMap
        System.out.println("--------------------扫描组件--------------------");
        componentScan();

        // 2.创建组件：单例Bean
        System.out.println("--------------------创建组件--------------------");
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            if ("singleton".equals(beanDefinition.getScope())) {
                singletonObjects.put(beanName, createBean(beanName, beanDefinition));
                System.out.println("创建单例Bean：" + beanName);
            }
        });
    }

    /**
     * 组件扫描
     * ComponentScan注解 --> 扫描路径 --> 扫描 --> BeanDefinition --> BeanDefinitionMap
     */
    private void componentScan() {

        if (!configClass.isAnnotationPresent(ComponentScan.class)) {
            System.out.println("配置类没有配置包扫描...");
            return;
        }

        // 1. 获取扫描路径
        ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
        String scanPath = componentScanAnnotation.value(); // com.xzy.service
        System.out.println("扫描路径：" + scanPath);
        scanPath = scanPath.replace(".", "/");

        // 2. 获取路径下的文件
        /*
         * 类加载器：
         *     Bootstrap ---> jre/lib
         *     Ext ---------> jre/ext/lib
         *     App ---------> classPath
         */
        ClassLoader classLoader = XiaozyApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(scanPath); // classpath:com/xzy/service
        File scanDirectory = new File(resource.getFile());// classpath = xxx/xxx/.../target/classes
        if (!scanDirectory.isDirectory()) {
            System.out.println("扫描地址有误");
            return;
        }
        File[] scanFiles = scanDirectory.listFiles();

        // 3. 处理路径下的文件
        for (File scanFile : scanFiles) {

            String scanFileAbsolutePath = scanFile.getAbsolutePath(); // xxx/xxx/.../target/classes/com/xzy/service/xxx.class
            if (!scanFileAbsolutePath.endsWith(".class")) {
                System.out.println("非class文件：" + scanFileAbsolutePath);
                continue;
            }
            String className = scanFileAbsolutePath.substring(scanFileAbsolutePath.indexOf("com"), scanFileAbsolutePath.indexOf(".class")); // com/xzy/service/XxxService
            className = className.replace("\\", "."); // com.xzy.service.XxxService
            System.out.print("扫描到类：" + className + " ");

            // 4. 处理Bean
            Class<?> clazz;
            try {
                clazz = classLoader.loadClass(className); // 通过类加载器获取.class对应的Class对象，以便解析Java类
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                continue;
            }
            if (!clazz.isAnnotationPresent(Component.class)) {
                System.out.println("非Bean");
                continue;
            }
            /*
             * 处理Bean......
             */
            Component componentAnnotation = clazz.getAnnotation(Component.class);
            String beanName = componentAnnotation.value(); // TODO:暂不实现以类名首字母小写为beanName

            // BeanPostProcessor
            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                try {
                    beanPostProcessorList.add((BeanPostProcessor) clazz.getDeclaredConstructor().newInstance());
                    System.out.println("后置处理器（直接创建）");
                    continue;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }

            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setClazz(clazz);
            if (!clazz.isAnnotationPresent(Scope.class) || clazz.getAnnotation(Scope.class).value().equals("singleton")) {
                // 单例Bean
                System.out.println("单例Bean");
                beanDefinition.setScope("singleton");
            } else {
                // 原型Bean
                System.out.println("原型Bean");
                beanDefinition.setScope("prototype");
            }

            beanDefinitionMap.put(beanName, beanDefinition);
        }
    }

    public Object getBean(String beanName) {
        if (!beanDefinitionMap.containsKey(beanName)) {
            throw new IllegalArgumentException("不存在的Bean：" + beanName);
        }

        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if ("singleton".equals(beanDefinition.getScope())) {
            // 单例Bean
            return singletonObjects.get(beanName);

        } else {
            // 原型Bean
            System.out.println("创建原型Bean：" + beanName);
            return createBean(beanName, beanDefinition);

        }

    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class<?> clazz = beanDefinition.getClazz();
        try {
            // 创建组件
            Object instance = clazz.getDeclaredConstructor().newInstance();

            // postProcessBeforeInitialization
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            // 依赖注入
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    Autowired autowiredAnnotation = declaredField.getAnnotation(Autowired.class);
                    String autowiredBean = autowiredAnnotation.value(); // TODO:暂不实现以类名首字母小写为beanName
                    Object bean = getBean(autowiredBean); // TODO: @Autowired注解的required属性

                    declaredField.setAccessible(true); // 修改访问权限
                    declaredField.set(instance, bean);
                }
            }

            // Aware回调
            if (instance instanceof BeanScopeAware) {
                ((BeanScopeAware) instance).setBeanScope(beanDefinition.getScope());
            }

            // 初始化
            if (instance instanceof InitializingBean) {
                try {
                    ((InitializingBean) instance).afterPropertiesSet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // postProcessAfterInitialization
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }

            return instance;

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
